/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.st.web;

import cn.hutool.core.codec.Base64;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.st.entity.*;
import com.jeesite.modules.st.pojo.AjaxJson;
import com.jeesite.modules.st.service.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 出入库单Controller
 *
 * @author HOHD
 * @version 2020-12-16
 */
@Controller
@RequestMapping(value = "${adminPath}/st/stInventoryBill")
public class StInventoryBillController extends BaseController {

    @Autowired
    private StInventoryBillService stInventoryBillService;

    /**
     * 获取数据
     */
    @ModelAttribute
    public StInventoryBill get(String id, boolean isNewRecord) {
        return stInventoryBillService.get(id, isNewRecord);
    }

    /**
     * 查询列表
     */
    @RequiresPermissions("st:stInventoryBill:view")
    @RequestMapping(value = {"list", ""})
    public String list(StInventoryBill stInventoryBill, Model model) {
        model.addAttribute("stInventoryBill", stInventoryBill);
        return "modules/st/stInventoryBillList";
    }

    @Autowired
    StWarehouseInventoryService stWarehouseInventoryService;

    @RequiresPermissions("st:stInventoryBill:view")
    @RequestMapping(value = {"materialChoose"})
    public String materialChoose(String warehouseNumber, String needNumber, Model model) {
        Map<String, Object> bean = new HashMap<>();
        bean.put("warehouseNumber", warehouseNumber);
        bean.put("needNumber", needNumber);
        model.addAttribute("bean", bean);
        return "modules/st/stInventoryBillForm-material-choose";
    }
    @RequiresPermissions("st:stInventoryBill:view")
    @RequestMapping(value = {"caseChoose"})
    public String caseChoose(String materialCode, Model model) {
        Map<String, Object> bean = new HashMap<>();
        StMaterialRecord query = new StMaterialRecord();
        query.setMaterialCode(materialCode);
        StMaterialRecord stMaterialRecord = stMaterialRecordService.findMP(query).get(0);
        String packType = stMaterialRecord.getPackType();
        bean.put("packType", packType);
        model.addAttribute("bean", bean);

        model.addAttribute("obj", stMaterialRecord);
        return "modules/st/stInventoryBillForm-out-bill-size-choose";
    }

    @RequiresPermissions("st:stInventoryBill:view")
    @RequestMapping(value = {"tableChoose"})
    public String tableChoose(StWarehouseInventory stWarehouseInventory, String json, Model model) throws IOException {
//        BASE64Decoder decoder = new BASE64Decoder();
//        Base64 base64=new
        String j = Base64.decodeStr(json);
//        List<Map<String,Object>> list=objectMapper.readValue(bytes, new TypeReference<List<Map<String,Object>>>() {
//        });

//        String j = new String(bytes);
        model.addAttribute("list", j);
//        String batchNumber = stWarehouseInventory.getBatchNumber();
////        String materialName = stWarehouseInventory.getMaterialName();//code 转化为id
//        String materialCode = stWarehouseInventory.getMaterialCode();
//        StMaterialRecord entity = new StMaterialRecord();
//        entity.setMaterialCode(materialCode);
//        List<StMaterialRecord> list1 = stMaterialRecordService.findList(entity);
//
//        StWarehouseInventory stWarehouseInventoryTemp = new StWarehouseInventory();
//        stWarehouseInventoryTemp.setBatchNumber(batchNumber);
//        stWarehouseInventoryTemp.setMaterialName(list1.get(0).getId());
//
//        List<StWarehouseInventory> list = stWarehouseInventoryService.getWarehouseNumber(true, stWarehouseInventoryTemp);
//        //添加唯一id
//        for (int i = 0; i < list.size(); i++) {
//            list.get(i).setId(i + "");
//        }
//        model.addAttribute("list", list);
        return "modules/st/stInventoryBillForm-table-choose";
    }

    /**
     * 查询列表数据
     */
    @RequiresPermissions("st:stInventoryBill:view")
    @RequestMapping(value = "listData")
    @ResponseBody
    public Page<StInventoryBill> listData(StInventoryBill stInventoryBill, HttpServletRequest request, HttpServletResponse response) {
        stInventoryBill.setPage(new Page<>(request, response));
        Page<StInventoryBill> page = stInventoryBillService.findPage(stInventoryBill);
        return page;
    }

    @Autowired
    StMaterialRecordService stMaterialRecordService;
    @Autowired
    StWarehousePositionSettingService stWarehousePositionSettingService;

    @Autowired
    StSupplierRecordService stSupplierRecordService;



    /**
     * 查看编辑表单
     */
    @RequiresPermissions("st:stInventoryBill:view")
    @RequestMapping(value = "form")
    public String form(StInventoryBill stInventoryBill, Model model) throws JsonProcessingException {
        List<StMaterialRecord> list = stMaterialRecordService.findList(new StMaterialRecord());
        List<StSupplierRecord> supplierList = stSupplierRecordService.findList(new StSupplierRecord());
        model.addAttribute("supplierList", supplierList);
        List<StWarehousePositionSetting> warehousePositionSettingList = stWarehousePositionSettingService.findList(new StWarehousePositionSetting());
        model.addAttribute("materialRecordList", objectMapper.writeValueAsString(list));
        model.addAttribute("warehousePositionSettingList", objectMapper.writeValueAsString(warehousePositionSettingList));
        model.addAttribute("stInventoryBill", stInventoryBill);
        return "modules/st/stInventoryBillForm";
    }
    @RequiresPermissions("st:stInventoryBill:view")
    @RequestMapping(value = "outBill")
    public String outBill(StInventoryBill stInventoryBill, Model model) throws JsonProcessingException {
        List<StMaterialRecord> list = stMaterialRecordService.findMP(new StMaterialRecord());
        List<StSupplierRecord> supplierList = stSupplierRecordService.findList(new StSupplierRecord());
        model.addAttribute("supplierList", supplierList);
        List<StWarehousePositionSetting> warehousePositionSettingList = stWarehousePositionSettingService.findList(new StWarehousePositionSetting());
        model.addAttribute("materialRecordList", objectMapper.writeValueAsString(list));
        model.addAttribute("warehousePositionSettingList", objectMapper.writeValueAsString(warehousePositionSettingList));
        model.addAttribute("stInventoryBill", stInventoryBill);
        return "modules/st/stInventoryBillForm-out-bill";
    }

    @RequiresPermissions("st:stInventoryBill:view")
    @RequestMapping(value = "purchaseIn")
    public String purchaseIn(StInventoryBill stInventoryBill, Model model) throws JsonProcessingException {
        List<StMaterialRecord> list = stMaterialRecordService.findList(new StMaterialRecord());
        List<StSupplierRecord> supplierList = stSupplierRecordService.findList(new StSupplierRecord());
        model.addAttribute("supplierList", supplierList);
        List<StWarehousePositionSetting> warehousePositionSettingList = stWarehousePositionSettingService.findList(new StWarehousePositionSetting());
        model.addAttribute("materialRecordList", objectMapper.writeValueAsString(list));
        model.addAttribute("warehousePositionSettingList", objectMapper.writeValueAsString(warehousePositionSettingList));
        model.addAttribute("stInventoryBill", stInventoryBill);
        return "modules/st/stInventoryBillForm-purchase-in";// 原来写的页面有点混了
    }
    @RequiresPermissions("st:stInventoryBill:view")
    @RequestMapping(value = "inventoryStatus")
    public String inventoryStatus(StInventoryBill stInventoryBill, Model model) throws JsonProcessingException {
        // 两个界面的单据类型值不一样

        List<StMaterialRecord> list = stMaterialRecordService.findMP(new StMaterialRecord());
        List<StSupplierRecord> supplierList = stSupplierRecordService.findList(new StSupplierRecord());
        model.addAttribute("supplierList", supplierList);
        List<StWarehousePositionSetting> warehousePositionSettingList = stWarehousePositionSettingService.findList(new StWarehousePositionSetting());
        model.addAttribute("materialRecordList", objectMapper.writeValueAsString(list));
        model.addAttribute("warehousePositionSettingList", objectMapper.writeValueAsString(warehousePositionSettingList));
        model.addAttribute("stInventoryBill", stInventoryBill);
        return "modules/st/stInventoryBillForm-inventory-status";
    }

    ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    StCustomRecordService stCustomRecordService;
    @Autowired
    StProductRecordService stProductRecordService;

    @RequiresPermissions("st:stInventoryBill:view")
    @RequestMapping(value = "saleOutForm")
    public String saleOutForm(StInventoryBill stInventoryBill, Model model) throws JsonProcessingException {
        List<StCustomRecord> customList = stCustomRecordService.findList(new StCustomRecord());
        model.addAttribute("customList", customList);
        List<StMaterialRecord> list = stMaterialRecordService.findList(new StMaterialRecord());
        List<StWarehousePositionSetting> warehousePositionSettingList = stWarehousePositionSettingService.findList(new StWarehousePositionSetting());
        List<StProductRecord> list1 = stProductRecordService.findList(new StProductRecord());
        model.addAttribute("materialRecordList", objectMapper.writeValueAsString(list1));
        model.addAttribute("warehousePositionSettingList", objectMapper.writeValueAsString(warehousePositionSettingList));
        model.addAttribute("stInventoryBill", stInventoryBill);
        return "modules/st/stInventoryBillForm-sale-out";
    }

    @Autowired
    StProductBillService stProductBillService;

    @RequiresPermissions("st:stInventoryBill:view")
    @RequestMapping(value = "completeProductForm")
    public String completeProductForm(StInventoryBill stInventoryBill, StProductBillBatchDetail stProductBillBatchDetail,
                                      @RequestParam(defaultValue = "2") Integer half,
//                                      Integer isInsert,
                                      Model model) throws JsonProcessingException {
        String cpIds = stProductBillBatchDetail.getCpIds();
        String halfKey //成品还是半成品的关键字
                = half == 1 ?
                "materialName" ://半成品
                "productName";
        model.addAttribute("halfKey", halfKey);
        int billType = half == 1 ? 32 : 31;
        model.addAttribute("in_or_out", billType);
        if (null != cpIds) {
            String[] ids = cpIds.split(",");
            stProductBillBatchDetail.setCpIdArr(ids);
            List<StProductBillBatchDetail> detailNoPage = stProductBillService.findDetailNoPage(stProductBillBatchDetail);
//        model.addAttribute("isInsert", isInsert);
//        model.addAttribute("detail", detailNoPage);
            List<StInventoryBillDetail> stInventoryBillDetailList = new ArrayList<>();
            for (StProductBillBatchDetail productBillBatchDetail : detailNoPage) {
                String productId = productBillBatchDetail.getProductId();
                StInventoryBillDetail stInventoryBillDetail = new StInventoryBillDetail();
                stInventoryBillDetail.setMaterialName(productId);
                if (1 == half) stInventoryBillDetail.setMaterialName(productBillBatchDetail.getMaterialId());//半成品
                stInventoryBillDetail.setUnit("KG");//todo 不能写死
                stInventoryBillDetail.setWarehousePosition("1351757854612439040");//todo 似乎也不应该写死
                Integer perWeight = productBillBatchDetail.getParentId().getPerWeight();
                stInventoryBillDetail.setNumber(perWeight);
                stInventoryBillDetail.setPackType(productBillBatchDetail.getSpecification());
                stInventoryBillDetail.setBatchNumber(productBillBatchDetail.getBatchNumber());
                stInventoryBillDetail.setBatchId(productBillBatchDetail.getId());
                stInventoryBillDetailList.add(stInventoryBillDetail);
            }
            stInventoryBill.setStInventoryBillDetailList(stInventoryBillDetailList);
        }
        List<StProductRecord> list = stProductRecordService.findList(new StProductRecord());
        List<StSupplierRecord> supplierList = stSupplierRecordService.findList(new StSupplierRecord());
        model.addAttribute("supplierList", supplierList);
        List<StWarehousePositionSetting> warehousePositionSettingList = stWarehousePositionSettingService.findList(new StWarehousePositionSetting());
        ObjectMapper objectMapper = new ObjectMapper();
        model.addAttribute("materialRecordList", objectMapper.writeValueAsString(list));
        if (half == 1) {//半成品是物料
            List<StMaterialRecord> list2 = stMaterialRecordService.findList(new StMaterialRecord());
            model.addAttribute("materialRecordList", objectMapper.writeValueAsString(list2));
        }

        model.addAttribute("warehousePositionSettingList", objectMapper.writeValueAsString(warehousePositionSettingList));


        model.addAttribute("stInventoryBill", stInventoryBill);
        return "modules/st/stInventoryBillForm-complete-product";
    }

    @RequestMapping("approve")
    @ResponseBody
    public AjaxJson approve(StInventoryBill stInventoryBill, Integer approveStatus, HttpServletRequest request, HttpServletResponse response) {
        AjaxJson<String> ajaxJson = new AjaxJson<>();
        stInventoryBill.setPage(new Page<>(request, response));
        String materialNameMsg = stInventoryBillService.approve(stInventoryBill, approveStatus);
        if (StringUtils.isNotBlank(materialNameMsg)) {
            ajaxJson.code = -1;
            ajaxJson.data = materialNameMsg ;
        }
        return ajaxJson;
    }
    @RequestMapping("take")
    @ResponseBody
    public AjaxJson take(StInventoryBill stInventoryBill, Boolean less,Boolean more) {
        AjaxJson<String> ajaxJson = new AjaxJson<>();
        stInventoryBillService.saveTakeStock(stInventoryBill, less, more);
        return ajaxJson;
    }

    /**
     * 保存数据
     */
    @RequiresPermissions("st:stInventoryBill:edit")
    @PostMapping(value = "save")
    @ResponseBody
    public String save(@Validated StInventoryBill stInventoryBill) {
        stInventoryBillService.save(stInventoryBill);
        stInventoryBill.setStInventoryBillDetailList(null);
        return renderResult(Global.TRUE, text("保存出入库单成功！"), stInventoryBill);
    }

    //    @Autowired
//    private StInventoryBillDetailDao stInventoryBillDetailDao;
    @PostMapping(value = "print")
    @ResponseBody
    public AjaxJson print(String printId, HttpServletResponse response) {
        AjaxJson<String> ajaxJson = new AjaxJson<>();
        ajaxJson.data = stInventoryBillService.print(printId);
        return ajaxJson;
    }

    @RequestMapping("pdf")
    public void pdf(String fileName, HttpServletResponse response) throws IOException {
        response.setContentType("application/pdf");
        //设置PDF文件名字，解决中文乱码问题
        response.setHeader("Content-Disposition",
                "attachment; filename=test.pdf");
        FileInputStream fis = null;
        OutputStream fos = response.getOutputStream();
        try {
            fis = new FileInputStream(new File(fileName)); // 建立文件输入流
            byte[] buffer = new byte[200];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
        } catch (FileNotFoundException ex) {
            System.out.println("Source File not found:" + fileName);
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        } finally {
            try {
                if (fis != null)
                    fis.close(); // 一定要进行文件的关闭,否则在新文件会是空的!
                if (fos != null)
                    fos.close();
            } catch (IOException ex) {
                System.out.println(ex);
            }
        }
    }

    /**
     * 删除数据
     */
    @RequiresPermissions("st:stInventoryBill:edit")
    @RequestMapping(value = "delete")
    @ResponseBody
    public String delete(StInventoryBill stInventoryBill) {
        stInventoryBillService.delete(stInventoryBill);
        return renderResult(Global.TRUE, text("删除出入库单成功！"));
    }

}